import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import externalGlobals from 'rollup-plugin-external-globals'
import { createHtmlPlugin } from 'vite-plugin-html'
import {
	pengWeiApp,
	zhinengwenshuApp,
	smartResumeApp,
	longgangApp,
	aibisenApp,
	mainApp,
} from './src/serves/prefixConfig'
import path from 'path'

// 打包后是否开启map和保留console
let debuggingCode = true

// 接口代理
let proxy = {
	// // 当前项目
	// '/volcengine': {
	// 	target: ' https://ark.cn-beijing.volces.com',
	// 	changeOrigin: true,
	// 	rewrite: (path: any) => {
	// 		return path.replace('/volcengine', '')
	// 	},
	// },
	// [mainApp.mainChatApi]: {
	// 	target: ' https://agent-demo.agent.echo-isoftstone.com',
	// 	changeOrigin: true,
	// 	rewrite: (path: string) => path.replace(new RegExp(`^${mainApp.mainChatApi}`), ''),
	// },
	// // 龙岗水务
	// [longgangApp.longgangChat]: {
	// 	target: 'http://172.18.4.158:11434',
	// 	changeOrigin: true,
	// 	rewrite: (path: string) => path.replace(new RegExp(`^${longgangApp.longgangChat}`), ''),
	// },
	// [longgangApp.longgangApiIntegration]: {
	// 	target: 'http://172.18.4.157:80',
	// 	changeOrigin: true,
	// 	rewrite: (path: string) => path.replace(new RegExp(`^${longgangApp.longgangApiIntegration}`), ''),
	// },
	// // 艾比森
	// [aibisenApp.aibisenChat]: {
	// 	target: 'https://abs-word.agent.echo-isoftstone.com',
	// 	changeOrigin: true,
	// 	rewrite: (path: string) => path.replace(new RegExp(`^${aibisenApp.aibisenChat}`), ''),
	// },
	// // 鹏微项目
	// [pengWeiApp.pengWeiWebApi]: {
	// 	target: 'http://10.37.17.18:8201',
	// 	changeOrigin: true,
	// 	rewrite: (path: string) => path.replace(new RegExp(`^${pengWeiApp.pengWeiWebApi}`), ''),
	// },
	// [pengWeiApp.pengWeiPythonApi]: {
	// 	target: 'http://10.37.17.18:8202',
	// 	changeOrigin: true,
	// 	rewrite: (path: string) => path.replace(new RegExp(`^${pengWeiApp.pengWeiPythonApi}`), ''),
	// },
	// // 智能问数
	// [zhinengwenshuApp.zhinengwenshuApi]: {
	// 	target: 'https://ai-wenshu.llm.gtsh.echo-isoftstone.cn',
	// 	changeOrigin: true,
	// 	rewrite: (path: string) => path.replace(new RegExp(`^${zhinengwenshuApp.zhinengwenshuApi}`), ''),
	// },
	// // 智能简历
	// [smartResumeApp.smartResumeApi]: {
	// 	target: 'http://123.249.71.102:39003', // http://10.37.87.229:9008 http://123.249.71.102:39003
	// 	changeOrigin: true,
	// 	rewrite: (path: string) => path.replace(new RegExp(`^${smartResumeApp.smartResumeApi}`), ''),
	// },
	// [smartResumeApp.parseApi]: {
	// 	target: 'http://10.37.87.229:9008', // http://10.37.87.229:9008 http://123.249.71.102:39003
	// 	changeOrigin: true,
	// 	rewrite: (path: string) => path.replace(new RegExp(`^${smartResumeApp.parseApi}`), ''),
	// },
	// // 测试demo
	// '/agentLlm': {
	// 	target: 'https://agent.llm.gtsh.echo-isoftstone.cn',
	// 	changeOrigin: true,
	// 	rewrite: (path: any) => {
	// 		return path.replace('/agentLlm', '')
	// 	},
	// },
	// '/testChat': {
	// 	target: 'http://172.18.4.157:80',
	// 	changeOrigin: true,
	// 	rewrite: (path: any) => {
	// 		return path.replace('/testChat', '')
	// 	},
	// },
	// // https://dev.usemock.com/676cff79512f14d276f92f09
	// '/shentie-test': {
	// 	target: 'https://dev.usemock.com/676cff79512f14d276f92f09',
	// 	changeOrigin: true,
	// },
}

// https://vite.dev/config/
export default ({ mode }: any) => {
	let env = loadEnv(mode, process.cwd())
	const { headHtml, externalGlobal } = configGlobalStatic()
	// console.log(externalGlobal, 'externalGlobal')
	return defineConfig({
		plugins: [
			vue(),
			createHtmlPlugin({
				minify: false,
				inject: {
					data: {
						title: '智能门户',
						isProd: env.VITE_USER_NODE_ENV !== 'development',
						headHtml,
					},
				},
			}),
		],
		resolve: {
			alias: {
				'@': path.resolve(__dirname, './src'),
			},
		},
		css: {
			preprocessorOptions: {
				// less: {
				// 	javascriptEnabled: true,
				// 	additionalData: `@import "${path.resolve(__dirname, 'src/style/variable.less')}";`,
				// },
			},
		},
		server: {
			host: true,
			open: false,
			proxy,
			port: 9091,
		},
		build: {
			outDir: env.VITE_OUT_DIR,
			sourcemap: debuggingCode,
			reportCompressedSize: false,
			chunkSizeWarningLimit: 1500,
			minify: 'terser',
			terserOptions: {
				// 移除调试
				compress: {
					drop_console: debuggingCode ? false : true,
					drop_debugger: debuggingCode ? false : true,
				},
			},
			rollupOptions: {
				// external: ['vue', 'element-plus', 'element-plus/dist/locale/zh-cn.mjs', 'axios'],
				external: [Object.keys(externalGlobal) as any],
				plugins: [externalGlobals(externalGlobal) as any],
				output: {
					chunkFileNames: 'static/js/[name]-[hash].js',
					entryFileNames: 'static/js/[name]-[hash].js',
					assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
					manualChunks(id: string) {
						if (id.includes('node_modules')) {
							const num = id.includes('.pnpm/') ? 2 : 1
							const name = id.toString().split('node_modules/')[num].split('/')[0].toString()
							// // js插件
							if (['axios', 'uuid4', 'dayjs-es', 'lodash-es', 'lsy-storages'].includes(name as any)) {
								return 'js_plugin'
							}
							// // vue插件
							if (['vue-router', 'pinia', '@vue', 'vue3-lazy'].includes(name as any)) {
								return '__vue_plugin'
							}
							// 其他自定义
							// docx-preview和docx-preview的其他依赖
							if (name.includes('docx-preview') || name.includes('jszip')) {
								return 'docx-preview'
							}
							return '___' + name
						}
					},
				},
			},
		},
	})
}

/**
 * 把常用的库定义成全局变量，通过js加入到html中
 * @returns {{ headHtml: string, externalGlobal: Object }} 返回包含头部HTML字符串和外部全局变量对象的对象
 */
function configGlobalStatic() {
	// 定义全局JavaScript文件的路径
	const jsGlobalPath = '/js'
	// const cssGlobalPath = '/css';
	// 如果版本需要更新到https://cdnjs.com/去找对应的版本的文件
	// 定义全局静态资源数组
	function setScriptStr(path: string) {
		return `<script src="${jsGlobalPath}/${path}" charset="UTF-8" defer></script>`
	}
	const globalStatic = [
		{
			// import时使用的名称
			name: 'vue',
			// 暴露的全局变量
			var: 'Vue',
			// js资源地址
			script: setScriptStr('vue.global.prod.min_3.5.13.js'),
		},
		{
			name: 'vue-demi',
			var: 'VueDemi',
			script: setScriptStr('vue-demi_index.iife.min_0.14.10.js'),
		},
		// {
		// 	name: 'vue-router',
		// 	var: 'VueRouter',
		// 	script: setScriptStr('vue-router.global.prod.min_4.5.0.js'),
		// },
		{
			name: 'element-plus',
			var: 'ElementPlus',
			script: setScriptStr('element-plus_index.full.min_2.9.1.js'),
		},
		{
			name: 'element-plus/dist/locale/zh-cn.mjs',
			var: 'ElementPlusLocaleZhCn',
			script: setScriptStr('element-plus_zh-cn.min_2.9.1.js'),
		},
		{
			name: '@element-plus/icons-vue',
			var: 'ElementPlusIconsVue',
			script: setScriptStr('element-plus_icons-vue_2.3.1.js'),
		},
		// {
		// 	name: 'axios',
		// 	var: 'axios',
		// 	script: setScriptStr('axios.min_1.7.9.js'),
		// },
		{
			name: 'luckyexcel',
			var: 'LuckyExcel',
			script: setScriptStr('luckyexcel_1.0.1.js'),
		},
		{
			name: 'mammoth',
			var: 'mammoth',
			script: setScriptStr('mammoth_1.9.0.js'),
		},
		// {
		// 	name: 'pinia',
		// 	var: 'Pinia',
		// 	script: setScriptStr('pinia.iife.prod.min_2.3.0.js'),
		// },
	]
	// 初始化头部HTML字符串
	let headHtml = ''
	// 初始化外部全局变量对象
	const externalGlobal: any = {}
	// 遍历全局静态资源数组
	globalStatic.forEach((c: any) => {
		// 拼接头部HTML字符串
		headHtml += (c?.script || '') + (c?.link || '')
		// 将name和var添加到外部全局变量对象中
		externalGlobal[c.name] = c.var
	})
	// console.log(headHtml, 'eh');
	// console.log(externalGlobal, 'externalGlobal');

	// 返回包含头部HTML字符串和外部全局变量对象的对象
	return {
		headHtml,
		externalGlobal,
	}
}
